<?php
namespace Common\Library;

class Aes
{
    /**
     * 算法
     */
    const CIPHER = MCRYPT_RIJNDAEL_256;

    /**
     * 模式
     */
    const MODE = MCRYPT_MODE_CBC;

    /**
     * 加密的盐
     * @var string
     */
    private static $salt = 'activity_wallet';

    /**
     * 处理特殊字符
     *
     * @param $string
     * @return mixed
     */
    private static function url_base64_encode($string)
    {
        $data = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($string));
        return $data;
    }

    /**
     * 解析特殊字符
     *
     * @param $string
     * @return string
     */
    private static function url_base64_decode($string)
    {
        $data = str_replace(['-', '_'], ['+', '/'], $string);
        $mod4 = strlen($data) % 4;

        if ($mod4) {
            $data .= substr('====', $mod4);
        }

        return base64_decode($data);
    }

    /**
     * md5 加盐加密
     * @param $string
     * @return string
     */
    private static function md5_salt($string)
    {
        return md5($string . self::$salt);
    }

    /**
     * AES 加密
     * @param $input 需要加密的数据
     * @param $key 秘钥
     * @return string 加密后的数据
     */
    public static function encrypt($input, $key)
    {
        $data = mcrypt_encrypt(self::CIPHER, self::md5_salt($key), $input, self::MODE, self::md5_salt(md5($key)));
        $data = base64_encode($data);
        $encrypted_string = trim(self::url_base64_encode($data));
        return $encrypted_string;
    }

    /**
     * AES 解密
     * @param $str 加密后的数据
     * @param $key 秘钥
     * @return string 解密后的数据
     */
    public static function decrypt($str, $key)
    {
        $base64_decode_string = self::url_base64_decode($str);
        $decrypted_string = trim(mcrypt_decrypt(self::CIPHER, self::md5_salt($key), base64_decode($base64_decode_string), self::MODE, self::md5_salt(md5($key))), "\0");
        return $decrypted_string;
    }

}